import React, { useState, useEffect, useCallback, useRef, } from 'react';
import {
  fetchStoresDetails,
  fetchStoresTypes,
  removePics,
  storesUpdate,
} from '@/services/platform/check'
import { Button, Form, Input, Row, Col, Cascader, Radio, Select, DatePicker, TimePicker, InputNumber, Upload, Icon, message, } from 'antd';
import { router } from 'umi';
import GapBlock from '@/components/GapBlock';
import UploadPic from '@/components/UploadPic';
import { formItemLayout } from '@/utils/utils';
import { connect } from 'dva';
import MyMap from './components/map';
import ProvincesCascader from '@/components/ProvincesCascader';
// import { Map, Marker   } from 'react-amap';

const { TextArea } = Input;
const { Option } = Select
const cooperateType = [
  {
    label: '直营',
    value: '1'
  },
  {
    label: '加盟',
    value: '2'
  },
  {
    label: '未知',
    value: '0'
  },
]
const industryIdList = [
  {
    label: "百货",
    value: '0'
  }
]

const StoreDetails = props => {
  const { form, location: { query }, distribute, dispatch, } = props
  const { getFieldDecorator } = form
  const { merchants, } = distribute
  const [data, setData] = useState({})
  const [mapPosition, setPosition] = useState({})
  const [locations, setLocations] = useState('')
  const [options, setOptions] = useState([])

  // 行业分类列表
  const [sTypes, setSTypes] = useState([])
  useEffect(() => {
    init({
      id: query.id
    })
    dispatch({
      type: 'distribute/fetchMerchants'
    })
    getStoreTypes()
  }, [])

  const init = async params => {
    const res = await fetchStoresDetails(params)
    setData(res.data)
    setPosition({
      lng: parseFloat(res.data.lon),
      lat: parseFloat(res.data.lat),
    })
  }

  const getStoreTypes = async (params = {pageSize: 999}) => {
    const res = await fetchStoresTypes(params)
    setSTypes(res.data)
  }

  const editStores = async params => {
    const res = await storesUpdate(params)
    res.code != 0 && message.warning(res.msg)
  }

  // 逻辑
  const handleConfirm = e => {
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      console.log('values', fieldsValue, mapPosition);
      editStores({
        ...data,
        ...fieldsValue,
        lat: mapPosition.lat,
        lon: mapPosition.lng,
        // 必填字段
        supplierId: 1,
        loginType: 1,
      }).then(() => {
        router.push('/platform/check/store')
      })
    })
  }

  const getPostion = (e, oth) => {
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      console.log('ads', e, oth)
    })
  }

  const getLocationName = (name, loc) => {
    setLocations(name)
    setPosition(loc)
  }

  const opt = options.map(d => <Option key={d.location}>{d.name}</Option>)
  return (
    <div>
      <Button type="primary" onClick={() => router.goBack()}>返回</Button>
      <GapBlock />
      <Form {...formItemLayout} onSubmit={handleConfirm}>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="所属商户">
              {getFieldDecorator('merchantsId', {
                initialValue: data.merchantsId,
                rules: [
                ],
              })(<Select>
                {merchants && merchants.map(m =>
                  <Option key={m.id}>{m.merchantName}</Option>
                )}
              </Select>)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="门店名称">
              {getFieldDecorator('name', {
                initialValue: data.name,
                rules: [
                ],
              })(<Input />)}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="合作类型">
              {getFieldDecorator('cooperateType', {
                initialValue: data.cooperateType,
                rules: [
                ],
              })(<Select>
                {cooperateType.map(c => <Option key={c.value}>{c.label}</Option>)}
              </Select>)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="店铺位置">
              {getFieldDecorator('storeAddress', {
                initialValue: [data.provinceId, data.cityId, data.areaId],
              })(
                <ProvincesCascader 
                  onlyCascader={true} 
                  onChange={val => console.log(val)}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="详细地址">
              {getFieldDecorator('address', {
                initialValue: locations || data.address,
                rules: [
                ],
              })(
                <Input onPressEnter={(e) => setLocations(e.target.value)} />
              )}
            </Form.Item>
          </Col>
          <Col>
            <Button type="primary" style={{ marginLeft: 10 }} onClick={getPostion}>查找</Button>
          </Col>
        </Row>
        <Row>
          <div style={{width: '100%', height: '400px'}}>
            <MyMap 
              mapPosition={mapPosition}
              getLocation={getLocationName}
            />
          </div>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="行业分类">
              {getFieldDecorator('parentCatId', {
                initialValue: data.parentCatId,
                rules: [
                ],
              })(
                <Select>
                  {sTypes.map(t =>
                    <Option key={t.id}>{t.catName}</Option>
                  )}
                </Select>
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="业务行业">
              {getFieldDecorator('industryId', {
                initialValue: data.industryId,
                rules: [
                ],
              })(
                <Select>
                  {industryIdList.map(i => <Option key={i.value}>{i.label}</Option>)}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="联系电话">
              {getFieldDecorator('phone', {
                initialValue: data.phone,
                rules: [
                ],
              })(<Input />)}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="联系人">
              {getFieldDecorator('contactPerson', {
                initialValue: data.contactPerson,
                rules: [
                ],
              })(<Input />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="营业状态">
              {getFieldDecorator('busStatus', {
                initialValue: data.busStatus,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>营业中</Radio>
                  <Radio value={'0'}>暂停营业</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="营业时间">
              {getFieldDecorator('businessTime', {
                rules: [
                  {
                    required: true,
                  }
                ],
              })(<TimePicker
                  format={"HH:mm"}
                />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="商品管理密码">
              {getFieldDecorator('goodsPwd', {
                initialValue: data.goodsPwd,
                rules: [
                ],
              })(<Input placeholder="商品管理密码(默认888888)" />)}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="营销管理密码">
              {getFieldDecorator('marketPwd', {
                initialValue: data.marketPwd,
                rules: [
                ],
              })(<Input placeholder="营销管理密码(默认888888)" />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="退款密码">
              {getFieldDecorator('refundPwd', {
                initialValue: data.refundPwd,
                rules: [
                ],
              })(<Input placeholder="退款密码(默认888888)" />)}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="排序">
              {getFieldDecorator('sort', {
                initialValue: data.sort,
                rules: [
                ],
              })(<InputNumber min={0} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="是否默认">
              {getFieldDecorator('isDefault', {
                initialValue: data.isDefault,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>是</Radio>
                  <Radio value={'0'}>否</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="是否上架">
              {getFieldDecorator('storeStatus', {
                initialValue: data.storeStatus,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>上架</Radio>
                  <Radio value={'0'}>下架</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="是否推荐到首页">
              {getFieldDecorator('isIndexRecommend', {
                initialValue: data.isIndexRecommend,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>推荐</Radio>
                  <Radio value={'0'}>不推荐</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="商户是否认证">
              {getFieldDecorator('isApproveStore', {
                initialValue: data.isApproveStore,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>认证</Radio>
                  <Radio value={'0'}>不认证</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="结算方式">
              {getFieldDecorator('storeType', {
                initialValue: data.storeType,
                rules: [
                ],
              })(
                <Radio.Group >
                  <Radio value={'1'}>机构结算</Radio>
                  <Radio value={'2'}>平台结算</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="部门代码">
              {getFieldDecorator('deptId', {
                initialValue: data.deptId,
                rules: [
                ],
              })(<Input />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="款台号">
              {getFieldDecorator('stationId', {
                initialValue: data.stationId,
                rules: [
                ],
              })(<Input />)}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="分店号">
              {getFieldDecorator('thirdPartyCode', {
                initialValue: data.thirdPartyCode,
                rules: [
                ],
              })(
                <Input />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="门店logo：">
              {getFieldDecorator('logo', {
                rules: [
                ],
              })(
                // upLoadComponent(data.supplierLogo, 1)
                <UploadPic
                  maxLoad={1}
                  imageUrl={data.supplierLogo}
                  action="/Amaidan-Goods-Web/common/uploadImage"
                  onRemove={file => {
                    // removePics({
                    //   imageId: file.uid
                    // }).then(res => {
                    //   if (res.code != 0) message.warning(res.msg)
                    // })
                  }}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="上传营业执照：">
              {getFieldDecorator('license', {
                rules: [
                ],
              })(
                <UploadPic
                  maxLoad={1}
                  imageUrl={data.openLicense}
                  action="/Amaidan-Goods-Web/common/uploadImage"
                  onRemove={file => {
                    // removePics({
                    //   imageId: file.uid
                    // }).then(res => {
                    //   if (res.code != 0) message.warning(res.msg)
                    // })
                  }}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="space-between">
          <Col span={8}>
            <Form.Item label="门店图片：">
              {getFieldDecorator('storePic', {
                rules: [
                ],
              })(
                <UploadPic
                  maxLoad={5}
                  imageUrl={data.storeImageList}
                  action="/Amaidan-Goods-Web/common/uploadImage"
                  handlePreview={file => console.log(file)}
                  onRemove={file => {
                    removePics({
                      imageId: file.uid
                    }).then(res => {
                      console.log(res)
                      if (res.code != 0) return message.warning(res.msg)
                      init({
                        id: query.id
                      })
                    })
                  }}
                />
              )}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="推广封面：">
              {getFieldDecorator('cover', {
                rules: [
                ],
              })(
                <UploadPic
                  maxLoad={1}
                  imageUrl={data.showingImage}
                  action="/Amaidan-Goods-Web/common/uploadImage"
                  onRemove={file => {
                    // removePics({
                    //   imageId: file.uid
                    // }).then(res => {
                    //   if (res.code != 0) message.warning(res.msg)
                    // })
                  }}
                />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="门店简介">
              {getFieldDecorator('storeDesc', {
                initialValue: data.storeDesc,
                rules: [
                ],
              })(<TextArea rows={4} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="门店公告">
              {getFieldDecorator('storeAffiche', {
                initialValue: data.storeAffiche,
                rules: [
                ],
              })(<TextArea rows={4} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row type="flex" justify="start">
          <Col span={8}>
            <Form.Item label="分享描述">
              {getFieldDecorator('desc', {
                initialValue: data.desc,
                rules: [
                ],
              })(<TextArea rows={4} />)}
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 16, offset: 8 },
          }}
        >
          <Button type="primary" htmlType="submit">
            审核
          </Button>
          <Button onClick={() => router.goBack()}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default connect(({ distribute }) => ({
  distribute,
}))(Form.create()(StoreDetails));
